package com.terabits.smartriver.controller;

import cn.hutool.core.date.DateUtil;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by zzk on 2020/1/16 0016
 */
public class DeadLock implements Runnable {
    Lock lock = new ReentrantLock();
    private Object lock1 = new Object();  // 两个锁对象
    private Object lock2 = new Object();

    @Override
    public void run() {
        while (true) {
            method1();
            method2();
        }
    }

    public void method1() {
        lock.lock();
        synchronized (lock1) {
            System.out.println(DateUtil.now() + Thread.currentThread().getName() + "获取到lock1");
            try {
                Thread.sleep(1000);  // 使得CPU切换
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            synchronized (lock2) {
                System.out.println(DateUtil.now() + Thread.currentThread().getName() + "获取到lock2");
            }
        }
    }

    public void method2() {
        lock.lock();
        synchronized (lock2) {
            System.out.println(DateUtil.now() + Thread.currentThread().getName() + "获取到--lock2");
            try {
                Thread.sleep(2000);  // 使得CPU切换
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            synchronized (lock1) {
                System.out.println(DateUtil.now() + Thread.currentThread().getName() + "获取到--lock1");
            }
        }
    }

    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock();
        new Thread(deadLock).start();
        new Thread(deadLock).start();
    }
}